'use strict';
const db = uniCloud.database();
const dbCmd = db.command
const $ = db.command.aggregate
const tools = require("../../tools/index.js")
const alioss = require('../../oss/index.js')
const Encryption_decryption = require('../../JSEncrypt/index.js')


// 获取版本列表
exports.SelVersionList = async function(body_data) {
	let res = {
		code:200,
		msg:"成功~"
	}
	let {UserInfo,AppId,Os,Version,content,forceUpdate,pageNum,pageSize} = body_data
	if (!pageNum.toString() || !pageSize) {return {msg: "pageNum/pageSize必传"}}
	
	let Skips = pageNum * pageSize
	let SelJson = {}
	let celue = ['AppId','Os','Version','content','forceUpdate']
	for(let i in celue){ 
		body_data[celue[i]]  ? SelJson[celue[i]]= body_data[celue[i]] :"" 
	}
	let Total = await db.collection('adminVersion').where(SelJson).count()
	let result = await db.collection('adminVersion').where(SelJson).limit(pageSize).skip(Skips).get()
	if(result.requestId){
		res.msg='查询成功~'
		res.data=result.data
		res.total = Total.total
	}else{
		res.msg='内部错误~'
		res.code=500
	}
	return res
}

// 添加版本
exports.AddVersion = async function(body_data) {
	let res = {
		code:200,
		msg:"成功~"
	}
	let {UserInfo,AppId,DownUrl,Os,Version,content,forceUpdate} = body_data
	if (!AppId || !DownUrl || !Os || !Version || !content || !forceUpdate) {return {msg: "参数错误"}}

	try{
		let result = await db.collection('adminVersion').add({AppId,DownUrl,Os,Version,content,forceUpdate,createTime:new Date(),IsCurrentUse:false})
		if(result.id){
			res.msg='插入数据成功~'
		}
	}catch(e){
		res.code = 500
		res.msg='内部错误，请联系管理员'
	}
	return res
}

// 删除版本
exports.DelVersion = async function(body_data) {
	let res = {
		code:200,
		msg:"成功~"
	}
	let {UserInfo,id} = body_data
	if (!id) {return {msg: "参数错误"}}
	let result = await db.collection('adminVersion').doc(id).remove()
	if(result.deleted>=1){
		res.msg='删除成功~'
	}else{
		res.msg='内部错误~'
		res.code=500
	}
	return res
}

// 修改更新版本
exports.UpdVersion = async function(body_data) {
	let res = {
		code:200,
		msg:"成功~"
	}
	let {UserInfo,_id,AppId,Os,Version,content,forceUpdate,DownUrl} = body_data
	 
	let result = await db.collection('adminVersion').doc(_id).update({AppId,Os,Version,content,forceUpdate,DownUrl})
	if(result.updated>=1){
		res.msg='更新成功~'
	}else if(result.updated===0){
		res.msg='更新未改变~'
	}else{
		res.msg='内部错误~'
		res.code=500
	}
	return res
}

// 指定当前使用的版本
exports.UpdCurrentUse = async function(body_data) {
	let res = { code:200, msg:"成功~" }
	let {UserInfo,_id,Os} = body_data
	await db.collection('adminVersion').where({Os: db.command.eq(Os)}).update({IsCurrentUse:false})
	// 设置当前当前这条数据的IsCurrentUse为true
	let result1 = await db.collection('adminVersion').doc(_id).update({IsCurrentUse:true})
	if(result1.updated>1){ // 更新成功~
		res.msg='设置成功~'
	}
	return res
}